/*
* Copyright (c) 2024 SwanLink (Jiangsu) Technology Development Co., LTD.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import 'package:flutter/services.dart';
import 'package:flutter_yfree/YFree.dart';
import 'package:universal_html/js.dart';

final myPlugin = MyPlugin();

class MyPlugin {
  final _myPlugin = const MethodChannel('MyPlugin');

  void _invokeMethod_async(method, {Map<String, dynamic>? arguments, Function(dynamic result)? onResult}) {
    if (yIsWeb) {
      yFreeWebPlugin!.invokeMethod(method, args: [JsObject.jsify(arguments ?? {}), (dynamic result) => onResult?.call(result)]);
    } else {
      _myPlugin.invokeMethod(method, arguments).then((result) {
        onResult?.call((result is Map) ? Map.from(result) : result);
      });
    }
  }

  dynamic _invokeMethod_sync<T>(method, {Map<String, dynamic>? arguments}) async {
    if (yIsWeb) {
      return await yRunCompleter((completer) {
        yFreeWebPlugin!.invokeMethod(method, args: [JsObject.jsify(arguments ?? {}), (dynamic result) => completer.complete(result)]);
      });
    } else {
      final result = await _myPlugin.invokeMethod(method, arguments);
      return (result is Map) ? Map.from(result) : result;
    }
  }
}
